import React, { useEffect, useState } from "react";
import { listDept, searchDeptList, delDept, findMaxSort, addDept, updateDept } from '@/api/system/dept'

import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Form } from "antd";
import { keepPreviousData, useQuery, useQueryClient } from "@tanstack/react-query";
import { expandTree, parseTime } from "../../../utils";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import { SvgIcon } from "@/components/icon";
import { useThemeToken } from "@/theme/hooks";
import DeptForm from "./modules/deptForm";

const queryItems = [
  {
    name: 'deptName',
    label: '组织名称',
    type: 'INPUT',
  },
  {
    name: 'deptCode',
    label: '组织编码',
    type: 'INPUT',
  }
];

//i18n
const DeptIndex = () => {
  const queryClient = useQueryClient()
  const [queryForm] = Form.useForm();
  // useWatch页面加载后在返回该页面会因为useWatch报错
  const queryParam = Form.useWatch((values) => values, queryForm)
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const confirm = Modal.confirm;
  const { colorLink } = useThemeToken();
  const columns = [
    {
      title: '组织名称',
      dataIndex: 'deptName',
      width: 300,
      render: (_, { deptName: text, deptType }) => {
        return text
        let icon = 'connections'
        let iconProps = {
          icon: icon,
          size: '20',
          color: colorLink,
          style: {
            marginTop: '-4px', marginRight: '8px'
          }
        }
        if (deptType === 'org') iconProps.icon = 'companyFill'
        if (deptType === 'company') iconProps.icon = 'company'
        if (text.indexOf(queryParam?.deptName) > -1) {
          return <><SvgIcon {...iconProps} />
            {text.substr(0, text.indexOf(queryParam?.deptName))}
            <span style={{ color: '#f50' }}> {queryParam?.deptName} </span>
            {text.substr(text.indexOf(queryParam?.deptName) + queryParam?.deptName.length)}
          </>
        } else {
          return <><SvgIcon {...iconProps} />{text}</>
        }
      }
    },
    {
      title: '组织编码',
      dataIndex: 'deptCode',
      render: (_, { deptCode: text }) => {
        if (text.indexOf(queryParam?.deptCode) > -1) {
          return <>
            {text.substr(0, text.indexOf(queryParam?.deptCode))}
            <span style={{ color: '#f50' }}> {queryParam?.deptCode} </span>
            {text.substr(text.indexOf(queryParam?.deptCode) + queryParam?.deptCode.length)}
          </>
        } else {
          return <>{text}</>
        }
      }
    },
    // {
    //   title: '区域名称',
    //   dataIndex: 'regionName',
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      ellipsis: true,
      align: 'center',
      render: (_, { createTime }) => (
        <>
          {parseTime(createTime)}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '240px',
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改组织`}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <DeptForm />
          </ModalForm>
          <Divider type="vertical" />
          <ModalForm
            trigger={<a>添加子组织</a>}
            title={`添加组织`}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            request={() => {
              return findMaxSort(record.id).then(res => {
                return { parentId: record.id, treeSort: res?.data, status: '0', deptType: 'dept' }
              })
            }}
            grid={true}
          >
            <DeptForm />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
        </>
      ),
    },
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-dept-listDept'],
    queryFn: () => {
      if (queryParam?.deptName || queryParam?.deptCode) {
        return searchDeptList({
          ...queryParam,
        }).then((res) => {
          setExpandedRowKeys(expandTree(res.data || [], 100))
          return res.data || []
        })
      } else {
        return listDept({}, '', 3).then((res) => {
          setExpandedRowKeys(expandTree(res.data || [], 3))
          return res.data || []
        })
      }
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
  }
  const onExpandCurrent = (expanded, record) => {
    //  展开收缩时需要动态修改展开行集合
    if (expanded) {
      setExpandedRowKeys([...expandedRowKeys, record.id])
    } else {
      setExpandedRowKeys(expandedRowKeys.filter(function (item) {
        return item !== record.id
      }))
    }
    if (expanded && (!record.children || !record.children.length)) {
      onLoadData(record)
    }
  }

  const saveData = (values) => {
    if (values.id) {
      return updateDept(values).then((res) => {
        if (res.data) {
          onLoadData({ id: values.parentId })
          message.success('修改成功')
          return true
        }
      })
    } else {
      return addDept(values).then((res) => {
        if (res.data) {
          // refetch()
          onLoadData({ id: values.parentId })
          message.success('新增成功')
          return true
        }
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return delDept(ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const onLoadData = (treeNode) => {
    return listDept({ ...queryParam }, treeNode.id, 1).then(({ data: child = [] }) => {
      const nowTree = updateTreeNode(tableData, treeNode.id, child)
      queryClient.setQueryData(['page-dept-listDept'], nowTree)
    })
  }

  // 递归查找并更新节点
  const updateTreeNode = (treeData, key, newData) => {
    return treeData.map((node) => {
      if (node.id === key) {
        return { ...node, children: newData || [] };
      }
      if (node.children) {
        return { ...node, children: updateTreeNode(node.children, key, newData) };
      }
      return node;
    });
  };

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">组织管理</div>
      <SearchForm
        onSearch={() => refetch()}
        items={queryItems}
        searchContent="查询"
        formRef={queryForm}
        buttons={<>
          <ModalForm
            trigger={<Button className="ml-2" icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加组织"
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            grid={true}
            request={() => {
              return findMaxSort(0).then(res => {
                return { treeSort: res?.data, status: '0', deptType: 'dept' }
              })
            }}
          >
            <DeptForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.id}
        loading={isFetching}
        dataSource={tableData || []}
        pagination={false}
        expandable={{
          expandedRowKeys: expandedRowKeys,
          onExpand: onExpandCurrent,
          expandIcon: ({ expanded, onExpand, record }) => {
            if (record.treeLeaf === 'y') {
              return <span style={{ 'marginRight': '22px' }}></span>
            } else if (expanded) {
              return <button style={{ color: colorLink, marginRight: '8px' }} onClick={e => onExpand(record, e)}><CaretDownOutlined /></button>
            } else {
              return <button style={{ color: colorLink, marginRight: '8px' }} onClick={e => onExpand(record, e)}><CaretRightOutlined /></button>
            }
          },
        }}
      />
    </div >
  );
};


export default DeptIndex;
